package com.example.mydownloader.netty.inBound

import com.example.mydownloader.mymodule.gson.GsonUtil
import com.example.mydownloader.mymodule.log.LogUtil
import com.example.mydownloader.netty.NettyMsg
import io.netty.buffer.ByteBuf
import io.netty.buffer.Unpooled
import io.netty.channel.ChannelHandlerContext
import io.netty.channel.ChannelInboundHandlerAdapter


/**
 * 自定义的Handler需要继承Netty规定好的HandlerAdapter
 * 才能被Netty框架所关联，有点类似SpringMVC的适配器模式
 */
class NettyMsgHandler : ChannelInboundHandlerAdapter() {

    override fun exceptionCaught(ctx: ChannelHandlerContext?, cause: Throwable?) {
        // 发生异常，关闭通道
        LogUtil.e(cause?.stackTraceToString())
        ctx?.close()
    }

    @Throws(Exception::class)
    override fun channelActive(ctx: ChannelHandlerContext) {
        val nettyMsg =
            NettyMsg(type = NettyMsg.NettyMsgType.Default, content = "channel of client is active")
        val jsonString = GsonUtil.toJson(nettyMsg)
        ctx.writeAndFlush(Unpooled.copiedBuffer(jsonString, Charsets.UTF_8))
    }

    override fun channelInactive(ctx: ChannelHandlerContext?) {
        super.channelInactive(ctx)
    }

    @Throws(Exception::class)
    override fun channelRead(ctx: ChannelHandlerContext, msg: Any) {
        val nettyMsg = msg as? NettyMsg
        LogUtil.d("收到服务端" + ctx.channel().remoteAddress().toString() + "的消息：" + nettyMsg)
    }

    override fun channelReadComplete(ctx: ChannelHandlerContext?) {
        LogUtil.d("channelReadComplete")
        super.channelReadComplete(ctx)
    }

    override fun userEventTriggered(ctx: ChannelHandlerContext?, evt: Any?) {
        super.userEventTriggered(ctx, evt)
    }

    override fun channelWritabilityChanged(ctx: ChannelHandlerContext?) {
        super.channelWritabilityChanged(ctx)
    }
}